package com.kabigon.tiny.dataSource.aspect;

import com.kabigon.tiny.dataSource.DataSourceType;
import com.kabigon.tiny.dataSource.anno.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 多数据源处理
 * @author xu.biao
 * @version v1.0
 * @Package com.kabigon.tiny.dataSource.aspect
 * @data 2022/12/17 20:18
 */
@Slf4j
@Aspect
@Order(1)
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.kabigon.tiny.dataSource.anno.DataSource)" +
            "|| @within(com.kabigon.tiny.dataSource.anno.DataSource)")
    public void dsPointCut(){}

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        DataSource dataSource = getDataSource(point);
        if (Objects.nonNull(dataSource)) {
            DataSourceType.setDataBaseType(dataSource.value());
        }

        try {
            return point.proceed();
        } finally {
            // 销毁数据源，在方法执行后
            DataSourceType.clearDataBaseType();
        }

    }

    /**
     * 获取需要切换的数据源
     * @param point
     * @return
     */
    private DataSource getDataSource(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }

}
